package Socket;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MultiCastChat extends JFrame {

	private static final long serialVersionUID = 1L;
	MulticastSocket socket; // 多播套接字
	InetAddress group;
	int port = 8888;
	JTextArea textarea = new JTextArea();
	JTextField textfield = new JTextField(22);
	DatagramPacket dp = null;

	public MultiCastChat() {
		super("客户端");
		Container con = getContentPane();
		con.setLayout(new BorderLayout());
		textarea.setEditable(false);

		con.add(new JScrollPane(textarea), BorderLayout.CENTER);
		con.add(southPanel(), BorderLayout.SOUTH);

		setSize(600, 500);
		setVisible(true);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				socket.close();
				System.exit(0);
			}
		});
	}

	private Component southPanel() {
		
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());

		JPanel panel2 = new JPanel();
		panel2.setLayout(new GridLayout(1, 2));
		JButton button = new JButton("发送");
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				sendMessage(socket, dp); // 发送数据包
			}

		});
		panel2.add(textfield);
		panel2.add(button);

		panel.add(panel2, BorderLayout.EAST);
		return panel;
	}

	public static void main(String[] args) {
		new MultiCastChat().startClient();
	}

	private void startClient() {
		
		try {
			socket = new MulticastSocket(port); // 用来发送和接收数据包的套接字
			group = InetAddress.getByName("226.1.3.5");
			socket.joinGroup(group); // 将socket加到这个组里完成登记
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		receiveMessage(socket, dp);
	}

	private void receiveMessage(MulticastSocket socket, DatagramPacket dp) {
		
		try {
			while (true) {
				byte[] buf = new byte[1024];
				dp = new DatagramPacket(buf, 1024); // 用于接收长度为1024的数据包，并将数据包的数据部分存在buf中
				socket.receive(dp);
				
				textarea.append(new String(buf).trim() + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			socket.close();
		}

	}

	private void sendMessage(MulticastSocket socket, DatagramPacket dp) {
		String str = textfield.getText();
		if (str != null && !str.trim().equals("")) {
			byte[] sendInfo = str.getBytes();
			try {
				// 将数据包发送到group组
				dp = new DatagramPacket(sendInfo, sendInfo.length, group, port);
				socket.send(dp); // 发送数据包
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		textfield.setText("");
	}
}